/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package io.netty.example.echo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.util.concurrent.DefaultProgressivePromise;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericProgressiveFutureListener;
import io.netty.util.concurrent.ProgressiveFuture;

public final class EchoServer {

    static final boolean SSL = System.getProperty("ssl") != null;
    static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));

    public static void main(String[] args) throws Exception {
        // Configure SSL.
        final SslContext sslCtx;
        if (SSL) {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } else {
            sslCtx = null;
        }

        // 创建一个boss线程组和一个worker线程组
        //首先来分析线程组的创建
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        //创建一个业务处理handler
        final EchoServerHandler serverHandler = new EchoServerHandler();
        try {
            //服务端启动辅助类
            ServerBootstrap b = new ServerBootstrap();
            //bossGroup是ServerChannel使用
            //workerGroup是基于当前Server产生的客户端Channel使用
            b.group(bossGroup, workerGroup)
                    //设置服务端channel类型，内部会创建一个反射工厂
                    //反射工厂那个提供了一个newInstance方法来创建channel 实例。
                    .channel(NioServerSocketChannel.class)
                    //保存一些server端的自定义选项
                    .option(ChannelOption.SO_BACKLOG, 100)
                    //配置用户自定义的server端pipeline处理器
                    //后续创建出NioServerSocketChannel实例后，会将用户自定义的Handler加入到该pipeline
                    .handler(new LoggingHandler(LogLevel.INFO))
                    //配置服务端上链接进来的客户端，客户端channel内部的pipeline初始化信息。
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            //这里是null，所以条件不成立，不会添加ssl相关的处理器
                            if (sslCtx != null) {
                                p.addLast(sslCtx.newHandler(ch.alloc()));
                            }
                            //添加一个日志处理器
                            p.addLast(new LoggingHandler(LogLevel.INFO));
                            //添加一个自定义的处理器
                            p.addLast(serverHandler);
                        }
                    });

            //bind方法返回一个与绑定操作相关的promise句柄
            ChannelFuture f = b.bind(PORT)
                    //这里其实是promise.sync()会将主线程陷入到挂起状态，直到绑定操作完成以后才会被唤醒。
                    .sync();


            f.channel().closeFuture().sync();
        } finally {
            // 优雅的关闭两个线程组
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    /**
     * 该方法是为了测试Future异步监听回调
     *
     * @param ctx
     * @param buf
     */
    private void FutureDemo(ChannelHandlerContext ctx, ByteBuf buf) {
        ChannelFuture promise = ctx.write(buf);
        promise.addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("SUCCESS");
            }
        });
        ctx.flush();
    }

    /**
     * 测试Future同步回调
     */
    private void FutureSyncDemo(ChannelHandlerContext ctx, ByteBuf buf) throws InterruptedException {
        ChannelFuture promise = ctx.write(buf);
        promise.sync();
        ctx.flush();
    }

    private void FutureCancel(ChannelHandlerContext ctx, ByteBuf buf) {
        ChannelFuture promise = ctx.write(buf);
        promise.cancel(false);
    }

    private void FutureProgressive(ChannelHandlerContext ctx) {
        DefaultProgressivePromise<Void> voidDefaultProgressivePromise = new DefaultProgressivePromise<>(ctx.executor());
        voidDefaultProgressivePromise.addListener(new GenericProgressiveFutureListener() {

            @Override
            public void operationComplete(Future future) throws Exception {
                System.out.println("operationComplete");
            }

            @Override
            public void operationProgressed(ProgressiveFuture future, long progress, long total) throws Exception {
                System.out.println("progress:" + progress + " total:" + total);
            }
        });
        voidDefaultProgressivePromise.tryProgress(1, 100);
        voidDefaultProgressivePromise.tryProgress(10, 100);
        voidDefaultProgressivePromise.setProgress(100, 100);
        voidDefaultProgressivePromise.setSuccess(null);
    }
}
